package com.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test {

    public static void main(String[] args) throws Exception {

//        test1(); //5803   5079  5472  5557
//        test2(); //8607  8889  9860  9417
        test3(); //227

    }

    //普通方式计算
    public static void test1() {
        Long sum = 0l;
        long start = System.currentTimeMillis();
        for (long i = 0l; i < 10_0000_0000l; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();

        System.out.println("sum=" + sum + "时间" + (end - start));

    }

    //forkJoin计算
    public static void test2() throws Exception {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinDemo(0l, 10_0000_0001l);
//        forkJoinPool.execute(task); //执行任务，没有结果（返回值）
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务，会有结果（返回值）
        Long sum = submit.get();
        System.out.println(sum);


        long end = System.currentTimeMillis();

        System.out.println("sum=" + sum + "时间" + (end - start));

    }

    //stream流计算
    public static void test3() {
        long start = System.currentTimeMillis();

        long sum = LongStream.rangeClosed(0l, 10_0000_0000L).parallel().reduce(0, Long::sum);

        long end = System.currentTimeMillis();

        System.out.println("sum=" + sum + "时间" + (end - start));

    }
}
